package net.joint_painting.client.controller;

import java.util.LinkedList;
import java.util.List;

import net.joint_painting.client.observer.TimeObserver;

import com.google.gwt.user.client.Timer;

/**
 * @author CAM
 * @version $Revision: 1.0 $
 */
public class TimeController {

    private Timer timer = null;
    int repeating = 10;
    Integer elapsedTime = 0;

    List<TimeObserver> observers = new LinkedList<TimeObserver>();

    public TimeController() {

    }

    /**
     * Method attach.
     * 
     * @param observer
     *            TimeObserver
     */
    public void attach(TimeObserver observer) {
	observers.add(observer);
    }

    /**
     * Method detach.
     * 
     * @param observer
     *            TimeObserver
     */
    public void detach(TimeObserver observer) {
	observers.remove(observer);
    }

    /**
     * Method notify.
     * 
     * @param elapsed
     *            Integer
     */
    private void notify(Integer elapsed) {
	for (int i = 0; i < observers.size(); i++) {
	    observers.get(i).update(elapsed);
	}
    }

    public void run() {
	timer = new Timer() {
	    @Override
	    public void run() {
		elapsedTime++;
		TimeController.this.notify(elapsedTime);
	    }
	};
	if (timer != null) {
	    timer.scheduleRepeating(repeating);

	}
    }

}
